from flask import Blueprint,render_template,g,redirect,request,jsonify
from app import db
from app.models import Product,User,Acctproduct,Updateturn,Updatejour,Updatepath,Bopupdateturn,UFTupdateturn
import os
import time
import paramiko
from app.method.web_methods import getboplist,getbopwar
import re



middle_server_page = Blueprint('middle_server_page',__name__,template_folder='templates')
@middle_server_page.route('/middle-server',methods = ['GET','POST'])
def middle_server():
    #判断用户是否在线或是否为空，不在线则重定向到login登陆界面
    if g.user is not None and g.user.is_authenticated:
        start_num=0
        stop_num=0
        #获取数据库中所有服务器数量
        server_num = len(db.session.query(Product).filter().all())
        #获取当前用户名
        hs_current_id = str(g.user).replace("'", "")
        hs_current_user = db.session.query(User.username).filter_by(id = hs_current_id).first()[0]
        #获取个人拥有的服务器
        pro_name = db.session.query(Acctproduct.server_name).filter_by(server_owner_id=hs_current_id).all()
        #获取个人通知信息
        mes_lists = db.session.query(Updatejour.output,Updatejour.update_date,Updatejour.update_time,Updatejour.message,Updatejour.id,Updatejour.log_path).filter_by(read_status = 1,up_persion=hs_current_user).all()
        mes_len = len(mes_lists)
        dirtime = str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())))
        server_lists = []
        #根据服务器名称去Product表获取该服务器所有信息
        for pro in pro_name:
            p_list = db.session.query(Product.server_name, Product.server_type, Product.server_address,
                                      Product.server_port,Product.server_user,Product.server_password, Product.creat_date, Product.edit_date,
                                      Product.edit_person).filter_by(server_name=pro[0]).all()
            server_lists.append(p_list)
        pre_server_num = len(server_lists)

        #处理前端请求逻辑
        if request.method == 'POST':

            #处理上传文件请求
            if request.files != None:
                #获取上传文件列表
                files = request.files.getlist('file')
                #拼串生成文件路径
                random_dirname = request.values.get('dirname')
                uppath_url = '/home/dar/download1/{}{}'.format(hs_current_user,random_dirname)

                #根据文件类别进行正则匹配文件分类，放到不同的文件夹下
                for f in files:
                    types = ['dll','cll','so','sql','xml','bpl','ini','xls','xlsx']
                    print(f.filename.split('.')[-1])
                    if f.filename.split('.')[-1] in types:
                        if f.filename in ['Report.dll', 'Default.xml', 'UPDSetup.ini']:
                            f.save(os.path.join(uppath_url + '/un_client/{}'.format(f.filename)))
                        elif f.filename in ['index.html', 'HSRCP.xml', 'deliver.ini', 'DELIVERX.INI', 'I18N.ini',
                                             'OneQueryConfig.ini', 'AllQueryConfig.ini', 'CommonQueryConfig.ini',
                                             'USERVOUC.INI', 'ScanConfig.ini']:
                            try:
                                os.makedirs(uppath_url+'/un_trade')
                            except:
                                pass
                            f.save(os.path.join(uppath_url + '/un_trade/{}'.format(f.filename)))
                        elif f.filename in ['Report.ini'] or re.match('.+.fr3', f.filename):
                            try:
                                os.makedirs(uppath_url+'/report')
                            except:
                                pass
                            f.save(os.path.join(uppath_url + '/report/{}'.format(f.filename)))
                        elif re.match('.+.so', f.filename) != None:
                            try:
                                os.makedirs(uppath_url+'/so')
                            except:
                                pass
                            f.save(os.path.join(uppath_url+'/so/{}'.format(f.filename)))
                        elif re.match('.+.ini', f.filename) != None:
                            try:
                                os.makedirs(uppath_url+'/ini')
                            except:
                                pass
                            f.save(os.path.join(uppath_url+'/ini/{}'.format(f.filename)))
                        elif re.match('.+.dll', f.filename) != None:
                            try:
                                os.makedirs(uppath_url+'/dll')
                            except:
                                pass
                            f.save(os.path.join(uppath_url + '/dll/{}'.format(f.filename)))
                        elif re.match('.+.sql', f.filename) != None:
                            try:
                                os.makedirs(uppath_url+'/sql')
                            except:
                                pass
                            f.save(os.path.join(uppath_url + '/sql/{}'.format(f.filename)))
                        elif re.match('.+.cll', f.filename) != None:
                            try:
                                os.makedirs(uppath_url+'/cll')
                            except:
                                pass
                            f.save(os.path.join(uppath_url + '/cll/{}'.format(f.filename)))
                        elif (re.match('.+.xls', f.filename) != None) or (re.match('.+.xlsx', f.filename) != None):
                            try:
                                os.makedirs(uppath_url+'/xls')
                            except:
                                pass
                            f.save(os.path.join(uppath_url + '/xls/{}'.format(f.filename)))
                        elif re.match('[\u4e00-\u9fa5].+.xml', f.filename) != None:
                            try:
                                os.makedirs(uppath_url+'/zn_xml')
                            except:
                                pass
                            f.save(os.path.join(uppath_url + '/zn_xml/{}'.format(f.filename)))
                        elif (re.match('[[a-z].+.xml', f.filename) != None) or (
                                re.match('[[A-Z].+.xml', f.filename) != None):
                            try:
                                os.makedirs(uppath_url+'/us_xml')
                            except:
                                pass
                            f.save(os.path.join(uppath_url + '/us_xml/{}'.format(f.filename)))
                        elif re.match('.+.bpl', f.filename) != None:
                            try:
                                os.makedirs(uppath_url+'/bpl')
                            except:
                                pass
                            f.save(os.path.join(uppath_url + '/bpl/{}'.format(f.filename)))

            # 处理打开服务器请求
            if request.values.get('fun')=='openSever':
                vm_name = request.values.get('id_num')
                #执行本地py文件
                os.system('python3 /home/dar/vmpy/openServer.py "{}"'.format(vm_name))
            # 处理关闭服务器请求
            elif request.values.get('fun')=='closeSever':
                vm_name1 = request.values.get('id_num')
                os.system('python3 /home/dar/vmpy/closeServer.py "{}"'.format(vm_name1))
            # 处理获取BOP取包和升级路径请求
            elif request.values.get('fun') == 'getpathname':
                bopip = request.values.get('bopip')
                #查询Updatepath表中对应ip的取包路径
                path_name = db.session.query(Updatepath.path_name).filter_by(server_ip=bopip,path_type=1).all()
                path_name_str = ''
                for name in path_name:
                    if path_name_str=='':
                        path_name_str = '请选择'+' '+name[0]
                    else:
                        path_name_str = path_name_str+' '+name[0]
                # 查询Updatepath表中对应ip的升级路径
                topath_name = db.session.query(Updatepath.path_name).filter_by(server_ip=bopip, path_type=2).all()
                topath_name_str = ''
                for toname in topath_name:
                    if topath_name_str == '':
                        topath_name_str = topath_name_str + toname[0]
                    else:
                        topath_name_str = topath_name_str + ' ' + toname[0]
                #返回给前台
                return jsonify({'path':path_name_str,'topath':topath_name_str})

            #上传文件升级方式进行表单提交的请求
            elif request.values.get('fun') == 'upload':
                #获取前端生成的时间戳
                up_path = request.values.get('random_path')
                #路径拼串
                up_path_new = '/home/dar/download1/{}{}'.format(hs_current_user,up_path)
                hs_host = request.values.get('host')
                hs_current_date = str(time.strftime('%Y%m%d', time.localtime(time.time())))
                #对应信息保存到升级信息表里
                hs_obj = Updateturn(output=up_path_new, up_host=hs_host,update_way=2, up_status=1,up_persion=hs_current_user, begin_date=hs_current_date)
                db.session.add(hs_obj)
                db.session.commit()

            #处理前端执行虚拟机中sh脚本的请求
            elif request.values.get('fun') == 'use_sh':
                #获取前端返回信息
                sh_path = request.values.get('sh_path')
                sh_name = request.values.get('sh_name')
                host = request.values.get('host')
                #查询对应服务器具体信息
                data = db.session.query(Product.server_port, Product.server_user, Product.server_password).filter_by(server_address=host).first()
                #模拟linux操作，实例化对象
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                #ssh连接
                ssh.connect(hostname=host, port=data[0], username=data[1], password=data[2])
                #执行命令
                stdin, stdout, stderr = ssh.exec_command('cd {} ;./{}'.format(sh_path,sh_name))
                result = stdout.read().decode("UTF-8").replace('\n', '')
                print(result)
                ssh.close()

            #调用getboplist方法，获取升级列表返回给前端
            elif request.values.get('fun')=='getbop':
                bopip = request.values.get('bopip')
                path_name = request.values.get('bopname')
                boplist = getboplist(bopip,path_name)
                return boplist

            # 调用getbopwar方法，获取升级war包列表返回给前端
            elif request.values.get('fun')=='getbop_version':
                version = request.values.get('version')
                path_name = request.values.get('bopname')
                bopip = request.values.get('bopip')
                print(path_name)
                bopwar = getbopwar(bopip,version,path_name)
                return bopwar

            # # 处理请求中获取tomcat唯一标识的请求
            # elif request.values.get("fun") == 'gettomcat_unique':
            #     bopip = request.values.get('bopip')
            #     path_name = request.values.get('pathname')
            #     tomcat_unique = get_tomcat_unique(bopip, path_name)
            #     return tomcat_unique

            elif request.values.get('fun')=='bopupdate':
                bop_upwar = ''
                bop_uppath = request.values.get('update_path')   # lable 选择版本
                bop_upwar_list = request.form.getlist('update_war')  # lable 选择升级文件
                bop_path_name = request.values.get('update_name')   # lable 选择取包路径
                bop_to_path_name = request.values.get('toupdate_name')  # lable 选择升级路径
                # bop_tomcat_unique = request.values.get('tomcat_unique')  # tomcat唯一标识符
                # if bop_tomcat_unique == '请选择' or bop_tomcat_unique == '' or bop_tomcat_unique is None:
                #     bop_tomcat_unique = ' '

                if len(bop_upwar_list) != 0:
                    for bop in bop_upwar_list:
                        if bop_upwar_list.index(bop) == 0:
                            bop_upwar = bop_upwar + bop
                        else:
                            bop_upwar = bop_upwar + ' ' + bop
                bop_ip = request.values.get('host')
                hs_current_date1 = str(time.strftime('%Y%m%d', time.localtime(time.time())))
                hs_obj = Bopupdateturn(bop_ip=bop_ip,bop_path=bop_uppath,bop_war=bop_upwar,up_status=1,up_persion=hs_current_user,path_name=bop_path_name,to_path_name=bop_to_path_name)
                db.session.add(hs_obj)
                db.session.commit()

            elif request.values.get('fun')=='update':
                hs_output = request.values.get('output')
                hs_version = request.values.get('version')
                hs_en_product =request.values.get('en_product')
                hs_host = request.values.get('host')
                hs_current_date = str(time.strftime('%Y%m%d', time.localtime(time.time())))
                hs_obj = Updateturn(output=hs_output,up_version=hs_version,en_product=hs_en_product,update_way=1,up_host=hs_host,up_status=1,up_persion=hs_current_user,begin_date=hs_current_date,progress='0,正在下载 请稍后')
                db.session.add(hs_obj)
                db.session.commit()
                return redirect('/middle-server')
            elif request.values.get('fun') == 'UFTupdate':
                hs_UFT_output = request.values.get('output')
                hs_UFT_version = request.values.get('version')
                hs_UFT_en_product = request.values.get('en_product')
                hs_UFT_host = request.values.get('host')
                hs_UFT_current_date = str(time.strftime("%Y%m%d",time.localtime(time.time())))
                hs_UFT_obj = UFTupdateturn(output = hs_UFT_output,up_version = hs_UFT_version,en_product = hs_UFT_en_product,update_way = 1,up_host = hs_UFT_host,up_status = 1,up_persion = hs_UFT_current_date,begin_date = hs_UFT_current_date,progress = '0,正在下载 请稍后')
                db.session.add(hs_UFT_obj)
                db.session.commit()
                return redirect('/middle-server')
            elif request.values.get('fun')=='deletemes':
                de_id = request.values.get('mes_id')
                u = Updatejour.query.filter_by(id = de_id).first()
                u.read_status = 2
                db.session.add(u)
                db.session.commit()
            elif request.values.get('fun')=='path':
                hs_path_name = request.values.get('path_name')
                hs_path_ip = request.values.get('path_ip')
                hs_path_port = request.values.get('path_port')
                hs_get_path =request.values.get('get_path')
                hs_host = request.values.get('host')
                hs_path_user = request.values.get('path_user')
                hs_path_password = request.values.get('path_password')

                rows = len(db.session.query(Updatepath).filter_by(path_name = hs_path_name).all())
                print(rows)
                if rows == 0:
                    hs_obj = Updatepath(path_type=1,path_ip=hs_path_ip,path_port=hs_path_port,get_path=hs_get_path,server_ip=hs_host,path_user=hs_path_user,path_password=hs_path_password,path_name=hs_path_name)
                    db.session.add(hs_obj)
                    db.session.commit()
                else:
                    u = Updatepath.query.filter_by(path_name = hs_path_name).first()
                    u.path_ip = hs_path_ip
                    u.path_port = hs_path_port
                    u.get_path = hs_get_path
                    u.path_user = hs_path_user
                    u.path_password = hs_path_password
                    db.session.add(u)
                    db.session.commit()
                z = Product.query.filter_by(server_address=hs_host).first()
                db.session.add(z)
                db.session.commit()

            elif request.values.get('fun')=='updatepath':
                hs_path_name = request.values.get('path_name')
                hs_path_ip = request.values.get('path_ip')
                hs_path_port = request.values.get('path_port')
                hs_to_path =request.values.get('to_path')
                hs_host = request.values.get('host')
                hs_path_user = request.values.get('path_user')
                hs_path_password = request.values.get('path_password')
                # hs_tomcat_unique = request.values.get('tomcat_unique')

                rows = len(db.session.query(Updatepath).filter_by(path_name = hs_path_name).all())
                print(rows)
                if rows == 0:
                    hs_obj = Updatepath(path_type=2,path_ip=hs_path_ip,path_port=hs_path_port,to_path=hs_to_path,server_ip=hs_host,path_user=hs_path_user,path_password=hs_path_password,path_name=hs_path_name)
                    db.session.add(hs_obj)
                    db.session.commit()
                else:
                    u = Updatepath.query.filter_by(path_name = hs_path_name).first()
                    u.path_ip = hs_path_ip
                    u.path_port = hs_path_port
                    u.get_path = hs_to_path
                    u.path_user = hs_path_user
                    u.path_password = hs_path_password
                    # u.tomcat_unique = hs_tomcat_unique
                    db.session.add(u)
                    db.session.commit()
                z = Product.query.filter_by(server_address=hs_host).first()
                db.session.add(z)
                db.session.commit()

    else:
        return redirect('/login')
    return render_template('hs-middle-server.html',hs_current_user=hs_current_user,server_lists=server_lists,pre_server_num=pre_server_num,server_num=server_num,stop_num=stop_num,start_num=start_num,mes_lists=mes_lists,mes_len=mes_len,value_random=dirtime)